﻿using System;
using System.ComponentModel;

namespace ThunderboltInterfaceSharp;

public class SimpleBackgroundWorker : IDisposable
{
	
	public delegate void WorkCompletedHandler();
	/// <summary>
	/// 工作完成事件
	/// </summary>
	public event WorkCompletedHandler WorkCompletedEvent;

	public delegate void WorkProcessHandler();
	/// <summary>
	/// 工作开始事件
	/// </summary>
	public event WorkProcessHandler WorkProcessEvent;

	
	public delegate void ProgressChangedHandler(int iPercentage);
	/// <summary>
	/// 工作进程改变事件
	/// </summary>
	public event ProgressChangedHandler ProcessChangedEvent;

	protected readonly BackgroundWorker Worker;

	public SimpleBackgroundWorker()
	{
		Worker = new BackgroundWorker();
		Worker.DoWork += new System.ComponentModel.DoWorkEventHandler(WorkerDoWork);
		Worker.WorkerReportsProgress = true;
		Worker.WorkerSupportsCancellation = true;
		Worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(WorkerRunWorkerCompleted);
		Worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(WorkerProgressChanged);
	}

	public void Start()
	{
		if (Worker.IsBusy)
			return;
		Worker.RunWorkerAsync();
	}

	public void Dispose()
	{
		Worker.Dispose();
	}
	/// <summary>
	/// 后台执行方法
	/// </summary>
	protected virtual void Process() { }
	/// <summary>
	/// 后台方法结束后执行
	/// </summary>
	protected virtual void Complete() { }

	private void WorkerDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
	{
		if (WorkProcessEvent != null)
		{
			WorkProcessEvent();
		}
		Process();
	}

	private void WorkerRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
	{
		if (WorkCompletedEvent != null)
		{
			WorkCompletedEvent();
		}
		Complete();
	}
	private void WorkerProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
	{
		if (ProcessChangedEvent != null)
		{
			ProcessChangedEvent(e.ProgressPercentage);
		}
	}
}